package com.zd.kids.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LanguageUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.StringUtils;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.hyy.language.CommonUtils;
import com.hyy.language.LanguageDataBean;
import com.hyy.language.SelectLanguageDialog;
import com.hyy.libray.common.BaseUtils;
import com.hyy.libray.common.Constant;
import com.hyy.libray.presenter.IBasePresenter;
import com.hyy.libray.ui.activity.BaseActivity;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.zd.kids.DataBean.CheackAppVersionDataBean;
import com.zd.kids.DataBean.MainGroupDataBean;
import com.zd.kids.DataBean.UserInfo;
import com.zd.kids.R;
import com.zd.kids.common.Constants;
import com.zd.kids.common.GlideUtil;
import com.zd.kids.common.ToastUtils;
import com.zd.kids.common.UserInfoConfig;
import com.zd.kids.net.CustomObserver;
import com.zd.kids.net.HttpMethod;
import com.zd.kids.ui.view.DownApkPopupWindow;
import com.zd.kids.ui.view.SelectBookTypePopupWindow;

import java.io.File;
import java.util.List;
import java.util.Locale;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.drawerlayout.widget.DrawerLayout;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MainTypeActivity extends BaseActivity {
    String installPerTips = StringUtils.getString(R.string.install_permission_tips);

    DownApkPopupWindow downApkPopupWindow;

    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.tv_version_name)
    TextView tvVersionName;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_name_top)
    TextView tvNameTop;
    @BindView(R.id.img_header)
    ImageView imgHeader;
    @BindView(R.id.drawer)
    DrawerLayout drawer;
    @BindView(R.id.ll_right_view)
    LinearLayout llRightView;
    @BindView(R.id.tv_study_1)
    TextView tvStudy1;
    @BindView(R.id.ll_status_1)
    LinearLayout llStatus1;
    @BindView(R.id.tv_study_2)
    TextView tvStudy2;
    @BindView(R.id.ll_status_2)
    LinearLayout llStatus2;
    @BindView(R.id.tv_study_3)
    TextView tvStudy3;
    @BindView(R.id.ll_status_3)
    LinearLayout llStatus3;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.tv_email)
    TextView tvEmail;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_book1_code)
    TextView tvBook1Code;
    @BindView(R.id.tv_book2_code)
    TextView tvBook2Code;
    @BindView(R.id.tv_book3_code)
    TextView tvBook3Code;
    @BindView(R.id.ll_book_code_1)
    LinearLayout llBookCode1;
    @BindView(R.id.ll_book_code_2)
    LinearLayout llBookCode2;
    @BindView(R.id.ll_book_code_3)
    LinearLayout llBookCode3;
    @BindView(R.id.tv_book1_title)
    TextView tvBook1Title;
    @BindView(R.id.tv_book2_title)
    TextView tvBook2Title;
    @BindView(R.id.tv_book3_title)
    TextView tvBook3Title;
    @BindView(R.id.view_statusbar)
    View viewStatusbar;
    @BindView(R.id.img_status_1)
    ImageView mImgStatus1;
    @BindView(R.id.tv_status_1)
    TextView mTvStatus1;
    @BindView(R.id.img_status_2)
    ImageView mImgStatus2;
    @BindView(R.id.tv_status_2)
    TextView mTvStatus2;
    @BindView(R.id.img_status_3)
    ImageView mImgStatus3;
    @BindView(R.id.tv_status_3)
    TextView mTvStatus3;
    @BindView(R.id.img_bootom)
    ImageView imgBootom;
    @BindView(R.id.img_header_icon)
    ImageView imgHeaderIcon;

    /**
     * 获取布局文件地址
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_main_type;
    }

    /**
     * 初始化布局
     */
    @Override
    public void initView() {

        ImmersionBar.with(this)
                .fullScreen(true)
                .hideBar(BarHide.FLAG_HIDE_BAR)
                .init();


        SpanUtils.with(tvTips)
                .append("GA")
                .setForegroundColor(0xffa92e37)
                .append("PSK")
                .setForegroundColor(0xff285f95)
                .create();

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewStatusbar.getLayoutParams();
        layoutParams.height = ImmersionBar.getStatusBarHeight(this);
        viewStatusbar.setLayoutParams(layoutParams);


        tvVersionName.setText("v" + AppUtils.getAppVersionName()
                + "," + ScreenUtils.getScreenDensity() + "," + ScreenUtils.getScreenDensityDpi()
                + "," + ScreenUtils.getScreenWidth() + "," + ScreenUtils.getScreenHeight()
                + "," + ScreenUtils.getAppScreenWidth() + "," + ScreenUtils.getAppScreenHeight()
        );

    }


    @Override
    public void initData() {
        super.initData();
        checkVersion();

    }

    /**
     * 获取Presenter，不用MVP，可以为空
     *
     * @return
     */
    @Override
    protected IBasePresenter onBasePresenter() {
        return null;
    }

    private SelectLanguageDialog selectLanguageDialog;

    private void showSelectLanguage() {
        if (selectLanguageDialog == null) {
            selectLanguageDialog = new SelectLanguageDialog(this);
            selectLanguageDialog.setOnclinckCallBack(new SelectLanguageDialog.OnclinckCallBack() {
                @Override
                public void onclinckCallBack(LanguageDataBean selectLanguage) {
                    if (selectLanguage != null && !TextUtils.isEmpty(selectLanguage.getCode())) {
                        Locale local = CommonUtils.getLanguageLocal(selectLanguage.getCode());
                        LanguageUtils.applyLanguage(local, true);
                        finish();
                    }
                }
            });
            selectLanguageDialog.setData(getString(R.string.select_language), getString(R.string.queren));
        }
        selectLanguageDialog.show();
    }

    @OnClick({R.id.img_header_icon, R.id.img_bootom, R.id.tv_languange, R.id.img_header, R.id.tv_outlogin, R.id.ll_status_1, R.id.ll_status_2, R.id.ll_status_3})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_languange:
                showSelectLanguage();
                break;
            case R.id.img_bootom:
                jumpToApmApp();
                break;
            case R.id.img_header:
                if (BaseUtils.isFastClick()) {
                    if (FileUtils.isDir(Constants.DATA_ROOT_PATH) && FileUtils.delete(Constants.DATA_ROOT_PATH)) {
                        ToastUtils.getIntence().makeTextShow("緩存清除成功");
                    }
                }
                break;
            case R.id.img_header_icon:
                drawer.openDrawer(llRightView);
                break;
            case R.id.ll_status_1:

                if (tvStudy1.getVisibility() != View.VISIBLE) {
                    new SelectBookTypePopupWindow(this, getString(R.string.yangfan)).showView();
                } else {
                    if (mMainGroupDataBeans != null && mMainGroupDataBeans.size() > 0) {
                        SPUtils.getInstance(Constant.GAPSK_AI_QM).put("GROUP_ID", mMainGroupDataBeans.get(0).getId() + "," + 0);
                        intent = new Intent(this, BookSeriesListActivity.class);
                        intent.putExtra(BookSeriesListActivity.GROUP_ID_KEY, mMainGroupDataBeans.get(0).getId());
                        startActivity(intent);
                    }

                }

                break;
            case R.id.ll_status_2:

                if (tvStudy2.getVisibility() != View.VISIBLE) {
                    new SelectBookTypePopupWindow(this, getString(R.string.bacui)).showView();
                } else {
                    if (mMainGroupDataBeans != null && mMainGroupDataBeans.size() > 1) {
                        SPUtils.getInstance(Constant.GAPSK_AI_QM).put("GROUP_ID", mMainGroupDataBeans.get(1).getId() + "," + 1);
                        intent = new Intent(this, BookSeriesListActivity.class);
                        intent.putExtra(BookSeriesListActivity.GROUP_ID_KEY, mMainGroupDataBeans.get(1).getId());
                        startActivity(intent);
                    }
                }


                break;
            case R.id.ll_status_3:

                if (tvStudy3.getVisibility() != View.VISIBLE) {
                    new SelectBookTypePopupWindow(this, getString(R.string.bacui)).showView();
                } else {

                    if (mMainGroupDataBeans != null && mMainGroupDataBeans.size() > 2) {
                        SPUtils.getInstance(Constant.GAPSK_AI_QM).put("GROUP_ID", mMainGroupDataBeans.get(2).getId() + "," + 2);
                        intent = new Intent(this, BookSeriesListActivity.class);
                        intent.putExtra(BookSeriesListActivity.GROUP_ID_KEY, mMainGroupDataBeans.get(2).getId());
                        startActivity(intent);
                    }
                }

                break;
            case R.id.tv_outlogin:

                new XPopup.Builder(this)
                        .dismissOnTouchOutside(false)
                        .asConfirm(getString(R.string.confirm_out), getString(R.string.sign_out_not_use), new OnConfirmListener() {
                            @Override
                            public void onConfirm() {

                                SPUtils.getInstance(Constant.GAPSK_AI_QM).put("jwt", "");
                                Intent intent = new Intent(MainTypeActivity.this, WelcomeActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                finish();
                            }
                        })
                        .show();

                break;
        }
    }

    private void jumpToApmApp() {
        if (AppUtils.isAppInstalled("com.gapsk.aet")) {
            startActivity(getPackageManager().getLaunchIntentForPackage("com.gapsk.aet"));
        } else {
            transferToGooglePlay("com.gapsk.aet");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getDatas();
        getUserInfo();
    }


    private List<MainGroupDataBean> mMainGroupDataBeans;

    private void getDatas() {
        showLoading();
        HttpMethod.getIntence().getMainGroupDatas(new CustomObserver<List<MainGroupDataBean>>() {
            @Override
            public void onSuccess(List<MainGroupDataBean> mainGroupDataBeans) {
                disLoading();
                mMainGroupDataBeans = mainGroupDataBeans;
                for (int i = 0; i < mainGroupDataBeans.size(); i++) {

                    MainGroupDataBean mainGroupDataBean = mainGroupDataBeans.get(i);
                    boolean groupBuy = mainGroupDataBean.isGroup_buy();
                    String title = mainGroupDataBean.getTitle();
                    if ("揚帆".equals(title)) {

                        if (groupBuy) {
                            llStatus1.setBackgroundResource(R.drawable.shape_main_type_bt);
                            tvStudy1.setVisibility(View.VISIBLE);
                        } else {
                            llStatus1.setBackgroundResource(R.drawable.shape_main_type_bt_local);
                            tvStudy1.setVisibility(View.GONE);
                        }

                        mTvStatus1.setVisibility(groupBuy ? View.GONE : View.VISIBLE);
                        mImgStatus1.setVisibility(groupBuy ? View.GONE : View.VISIBLE);

                    } else if ("綻放".equals(title)) {
                        if (groupBuy) {
                            llStatus2.setBackgroundResource(R.drawable.shape_main_type_bt);
                            tvStudy2.setVisibility(View.VISIBLE);
                        } else {
                            llStatus2.setBackgroundResource(R.drawable.shape_main_type_bt_local);
                            tvStudy2.setVisibility(View.GONE);
                        }
                        mTvStatus2.setVisibility(groupBuy ? View.GONE : View.VISIBLE);
                        mImgStatus2.setVisibility(groupBuy ? View.GONE : View.VISIBLE);
                    } else if ("拔萃".equals(title)) {
                        if (groupBuy) {
                            llStatus3.setBackgroundResource(R.drawable.shape_main_type_bt);
                            tvStudy3.setVisibility(View.VISIBLE);
                        } else {
                            llStatus3.setBackgroundResource(R.drawable.shape_main_type_bt_local);
                            tvStudy3.setVisibility(View.GONE);
                        }
                        mTvStatus3.setVisibility(groupBuy ? View.GONE : View.VISIBLE);
                        mImgStatus3.setVisibility(groupBuy ? View.GONE : View.VISIBLE);

                    }
                }
            }

            @Override
            public void onError(String errorCode) {
                disLoading();
            }
        });
    }

    private void getUserInfo() {
        HttpMethod.getIntence().getUserInfo(new CustomObserver<UserInfo>(this) {
            @Override
            public void onSuccess(UserInfo userInfo) {

                UserInfoConfig.getInstance().setAccount(userInfo.getCountrycode() + userInfo.getMobile());

                UserInfoConfig.getInstance().setName(userInfo.getName());

                GlideUtil.loadRoundCircle(userInfo.getPhoto(), imgHeader, R.mipmap.ic_default_header);
                GlideUtil.loadRoundCircle(userInfo.getPhoto(), imgHeaderIcon, R.mipmap.ic_default_header);

                tvName.setText(userInfo.getName());
                tvNameTop.setText(userInfo.getName());

                tvBirthday.setText(BaseUtils.getDateToString(userInfo.getBirthday() * 1000));

                tvEmail.setText(userInfo.getEmail());

                tvMobile.setText(userInfo.getMobile());

                tvAge.setText(userInfo.getAge());
                List<UserInfo.ResultBean> resultBeans = userInfo.getResult();
                for (int i = 0; i < resultBeans.size(); i++) {
                    UserInfo.ResultBean resultBean = resultBeans.get(i);
                    if (i == 0) {
                        tvBook1Code.setText(resultBean.isStatus() ? resultBean.getClassroomid() : "");
                        llBookCode1.setBackgroundResource(resultBean.isStatus() ? R.drawable.shape_main_type_series_select : R.drawable.shape_main_type_series_default);
                    } else if (i == 1) {
                        tvBook2Code.setText(resultBean.isStatus() ? resultBean.getClassroomid() : "");
                        llBookCode2.setBackgroundResource(resultBean.isStatus() ? R.drawable.shape_main_type_series_select : R.drawable.shape_main_type_series_default);
                    } else if (i == 2) {
                        tvBook3Code.setText(resultBean.isStatus() ? resultBean.getClassroomid() : "");
                        llBookCode3.setBackgroundResource(resultBean.isStatus() ? R.drawable.shape_main_type_series_select : R.drawable.shape_main_type_series_default);
                    }
                }

            }

            @Override
            public void onError(String errorCode) {

            }
        });
    }

    private static final int TIME_EXIT = 2000;

    private long mBackPressed;

    @Override
    public void onBackPressed() {
        if (mBackPressed + TIME_EXIT > System.currentTimeMillis()) {
            super.onBackPressed();
            System.exit(0);
            return;
        } else {
            ToastUtils.getIntence().makeTextShow(getString(R.string.double_click_exit));
            mBackPressed = System.currentTimeMillis();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1996) {
            checkInstallPermission();
        }
    }

    private void checkInstallPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            if (!getPackageManager().canRequestPackageInstalls()) {
                downApkPopupWindow.hidePrograss();
                downApkPopupWindow.setPromptContent(installPerTips);
                return;
            }
        }

        File apkFile = new File(filePathName);

        Intent intent = new Intent(Intent.ACTION_VIEW);
//      安装完成后，启动app（源码中少了这句话）

        if (null != apkFile) {
            try {
                //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileProvider", apkFile);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    //兼容8.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        boolean hasInstallPermission = this.getPackageManager().canRequestPackageInstalls();
                        if (!hasInstallPermission) {
                            return;
                        }
                    }
                } else {
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
                if (getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                    startActivity(intent);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    String filePathName;

    private void downApk(String urlPath) {
        String fileNam = urlPath.substring(urlPath.lastIndexOf("/"));
        if (FileUtils.isFileExists(Constants.COMMON_ROOT_PATH + fileNam)) {
            FileUtils.delete(Constants.COMMON_ROOT_PATH + fileNam);
//            installAPK(Constants.COMMON_ROOT_PATH + fileNam);
//            return;
        }
        FileUtils.createFileByDeleteOldFile(Constants.COMMON_ROOT_PATH + fileNam);
        HttpMethod.getIntence().downFile(urlPath, new File(Constants.COMMON_ROOT_PATH + fileNam), new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer integer) {
                downApkPopupWindow.showPrograss();
                downApkPopupWindow.setPromptContent(getString(R.string.app_name) + " down: " + integer + "%");
                downApkPopupWindow.setDownProgress(integer);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getIntence().makeTextShow(getString(R.string.data_error_tips));
            }

            @Override
            public void onComplete() {
                installAPK(Constants.COMMON_ROOT_PATH + fileNam);
            }
        });
    }


    private void checkVersion() {
        HttpMethod.getIntence().checkApkVersion(new CustomObserver<CheackAppVersionDataBean>(this) {
            @Override
            public void onSuccess(CheackAppVersionDataBean cheackAppVersionDataBean) {

                if (cheackAppVersionDataBean.getVersion() > AppUtils.getAppVersionCode()) {
                    downApkPopupWindow = new DownApkPopupWindow(MainTypeActivity.this);
                    downApkPopupWindow.setCallBack(new DownApkPopupWindow.CallBack() {
                        @Override
                        public void confirm() {

                            if (installPerTips.equals(downApkPopupWindow.getPromptContent())) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    if (!getPackageManager().canRequestPackageInstalls()) {
                                        Uri packUri = Uri.parse("package:" + getPackageName());
                                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packUri);
                                        startActivityForResult(intent, 1996);
                                        return;
                                    }
                                }

                                checkInstallPermission();

                            } else {

                                if ("0".equals(cheackAppVersionDataBean.getUpdate_mode())) {
                                    downApk(cheackAppVersionDataBean.getDownload_path());
                                } else {
                                    transferToGooglePlay("com.zd.kids");
                                }

                            }
                        }

                        @Override
                        public void cancle() {

                        }

                        @Override
                        public void onShow() {
                            downApkPopupWindow.setPromptTitle(cheackAppVersionDataBean.getTitle());
                            downApkPopupWindow.setPromptContent(cheackAppVersionDataBean.getDesc());
                            downApkPopupWindow.setForce(cheackAppVersionDataBean.getForce_ver() > AppUtils.getAppVersionCode());
                            downApkPopupWindow.setPromptContent(cheackAppVersionDataBean.getDesc());
                            downApkPopupWindow.hidePrograss();
                        }
                    });
                    downApkPopupWindow.showView();

                }

            }

            @Override
            public void onError(String errorCode) {

            }
        });
    }

    String googlePlay = "com.android.vending";

    private void transferToGooglePlay(String packName) {
        try {
            Uri uri = Uri.parse("market://details?id=" + packName);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(googlePlay)) {
                intent.setPackage(googlePlay);
            }
            if (intent.resolveActivity(getPackageManager()) != null) { //可以接收
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else { //没有应用市场，我们通过浏览器跳转到Google Play
                intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + packName));
                //这里存在一个极端情况就是有些用户浏览器也没有，再判断一次
                if (intent.resolveActivity(getPackageManager()) != null) { //有浏览器
                    startActivity(intent);
                } else { //天哪，这还是智能手机吗？
                    ToastUtils.getIntence().makeTextShow(getString(R.string.install_google));
                }
            }

        } catch (Exception e) {
            ToastUtils.getIntence().makeTextShow(getString(R.string.install_google));
        }

    }


    /**
     * 安装Apk
     */
    private void installAPK(String filePath) {
        filePathName = filePath;
        checkInstallPermission();
    }

}
